import { readFileSync, readdirSync, writeFileSync } from "fs";
import { join } from "path";

let first: string[] = ['Const.json', 'Sound.json', 'Title.json', 'School.json', 'Mouse.json', 'Duty.json', 'Store.json', 'Skill.json', 'SchoolGate.json', 'Sign.json']

let type = 'wx';// wx

let path = process.cwd();
let tableCfgStr = readFileSync(join(path, 'bin/table.json')).toString();
let tableCfg = JSON.parse(tableCfgStr);
let filePath = join(tableCfg.jsonPath)
let files = readdirSync(filePath);
let fn = files.filter(f => f == '_filelist_.json')[0];
let targetFn = 'table.ts';
let targetFn2 = 'table2.js';
let firstContent = 'export var table = {\n'
let secondContent = 'var table2 = {\n'
if (fn) {
    let fileListStr = readFileSync(join(tableCfg.jsonPath, fn)).toString();
    firstContent += getFileContent(fn, fileListStr);
    let fileList: string[] = JSON.parse(fileListStr);
    fileList.forEach(fl => {
        let str = readFileSync(join(tableCfg.jsonPath, fl)).toString();
        if (type == 'web') {
            firstContent += getFileContent(fl, str);
        } else {
            if (first.indexOf(fl) >= 0) {
                firstContent += getFileContent(fl, str);
            } else {
                secondContent += getFileContent(fl, str);
            }
        }
    })

    firstContent += '};'
    secondContent += '};\nmodule.exports = table2;'
    if (type == 'web') {
        writeFileSync(join(tableCfg[type + 'Path'], targetFn), firstContent)
    } else {
        let wxpathTemp = tableCfg[type + 'Path'] + '';
        let wxpaths = wxpathTemp.split(',');
        writeFileSync(join(wxpaths[0], targetFn), firstContent)
        writeFileSync(join(wxpaths[1], targetFn2), secondContent)
    }
}

function getFileContent(fn: string, content: string) {
    let fn0 = fn.split('.')[0];
    let txt = `\n${fn0} : ${content},\n`;
    return txt;
}